package com.bestv.search.engine.task;

import com.bestv.search.common.cache.SystemCache;
import com.bestv.search.engine.command.InfoCommand;
import com.bestv.search.engine.command.SuggestCommand;
import com.bestv.search.engine.command.TopNCommand;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @author Michael Wang
 */
public class IndexKeywordForSuggestion extends QuartzJobBean {

    static boolean isRunning = false;
    Logger logger = Logger.getLogger(IndexKeywordForSuggestion.class);
    private TopNCommand topNCommand;
    private InfoCommand infoCommand;
    private SystemCache systemCache;
    private SuggestCommand suggestCommand;

    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        if (!isRunning) {
            isRunning = true;
            run();
        } else {
            logger.error("Last suggestion index process is still running");
        }
    }

    private void run() {
        logger.info("Start suggestion index @" + new Date());
        try {
            suggestCommand.createOrUpdateIndex();
        } catch (Exception e) {
            logger.error("Suggestion index failed @" + new Date());
            e.printStackTrace();
        }

        logger.info("End suggestion index @" + new Date());
        isRunning = false;
    }

    public TopNCommand getTopNCommand() {
        return topNCommand;
    }

    public void setTopNCommand(TopNCommand topNCommand) {
        this.topNCommand = topNCommand;
    }

    public InfoCommand getInfoCommand() {
        return infoCommand;
    }

    public void setInfoCommand(InfoCommand infoCommand) {
        this.infoCommand = infoCommand;
    }

    public SystemCache getSystemCache() {
        return systemCache;
    }

    public void setSystemCache(SystemCache systemCache) {
        this.systemCache = systemCache;
    }

    public SuggestCommand getSuggestCommand() {
        return suggestCommand;
    }

    public void setSuggestCommand(SuggestCommand suggestCommand) {
        this.suggestCommand = suggestCommand;
    }
}
